from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
import logging
import base64
import cgi

from google.appengine.api import mail
from google.appengine.ext import db

import urllib
from google.appengine.api import urlfetch

import xml.dom.minidom
from django.utils import simplejson

import Cametrics
import config

class main(webapp.RequestHandler):
	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
		self.response.out.write(template.render(path, config.getTemplateValues()))
		#self.response.headers['Content-Type'] = 'text/plain'
		#self.response.out.write('In general this is kind of annoying!')

class stats(webapp.RequestHandler):
        def get(self):
                path = os.path.join(os.path.dirname(__file__), 'templates/stats.html')
                self.response.out.write(template.render(path, config.getTemplateValues()))

class statsmobile(webapp.RequestHandler):
        def get(self):
                path = os.path.join(os.path.dirname(__file__), 'templates/statsmobile.html')
                self.response.out.write(template.render(path, config.getTemplateValues()))


class participate(webapp.RequestHandler):
        def get(self):
                path = os.path.join(os.path.dirname(__file__), 'templates/participate.html')
                self.response.out.write(template.render(path, config.getTemplateValues()))

class document(webapp.RequestHandler):
        def get(self):
                path = os.path.join(os.path.dirname(__file__), 'templates/document.html')
                self.response.out.write(template.render(path, config.getTemplateValues()))

class map(webapp.RequestHandler):
        def get(self):
                path = os.path.join(os.path.dirname(__file__), 'templates/map.html')
                self.response.out.write(template.render(path, config.getTemplateValues()))

class mapmobile(webapp.RequestHandler):
        def get(self):
                path = os.path.join(os.path.dirname(__file__), 'templates/mapmobile.html')
                self.response.out.write(template.render(path, config.getTemplateValues()))

class androidsloglocation(webapp.RequestHandler):
        
        def post(self):
                
                # Acts as pass through
                logging.info(self.request.body)
                result = urlfetch.fetch(url="http://sensorbase.org/upload.php", payload=self.request.body, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, deadline=10)

                # Return this for Cammpaignr!
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write('Dispatched correctly.\n')

class androidslogmode(webapp.RequestHandler):
        
        def post(self):
                
                # Acts as pass through
                logging.info(self.request.body)
                result = urlfetch.fetch(url="http://sensorbase.org/upload.php", payload=self.request.body, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, deadline=10)

                # Return this for Cammpaignr!
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write('Dispatched correctly.\n')

class androidslogimage(webapp.RequestHandler):

        def dumper(self):
                for key in self.request.params.keys():
                        value = self.request.get(key)
                        logging.info(key+':'+value+'\n')

        def post(self):

		Cametrics.initialize(config.cametricskey)

		file_data = self.request.POST.get('file').file.read()
		file_name = self.request.POST.get('file').filename

		username = self.request.POST.get('username')

		type = self.request.POST.get('tags')
		type = type.replace(" ", "")
		type = type.lower()

		timestamp = self.request.POST.get('time')
		timestamp = timestamp.split(" ")
		timestamp = timestamp[0]
		latitude = self.request.POST.get('latitude')
		longitude = self.request.POST.get('longitude')

		#logging.info(file_data)
		logging.info("File Name: " + file_name)
		logging.info("Username: " + username)
		logging.info("Type: " + type)
		logging.info("Timestamp: " + timestamp)
		logging.info("Latitude: " + latitude)
		logging.info("Longitude: " + longitude)

		# Cametrics Measurements
		Cametrics.measure("type", type, "string")
		Cametrics.measure("users", username, "string")

		if((str(latitude) != "") and (str(longitude) != "")):
			Cametrics.measure("locations", str(longitude)+","+str(latitude), "location")
			Cametrics.measure(type, str(longitude)+","+str(latitude), "location")
			Cametrics.measure(username, str(longitude)+","+str(latitude), "location")

		Cametrics.commit()

		image = base64.encodestring(file_data)

                # This is to post things to flickr
		form_fields = config.getFlickrValues()
		form_fields.update({ "tags":type+" "+username, "latitude":str(latitude), "longitude":str(longitude), "image":image, "title":timestamp })

                form_data = urllib.urlencode(form_fields)
                result = urlfetch.fetch(url="http://whatsinvasive.com/research/slogtoflickr.php", payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, deadline=10)

                # Return this for Android!
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write('Dispatched correctly.\n')

class campaignrsloglocation(webapp.RequestHandler):

	def post(self):

		# Acts as pass through 
		logging.info(self.request.body)
		result = urlfetch.fetch(url="http://sensorbase.org/upload.php", payload=self.request.body, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, deadline=10)

                # Return this for Cammpaignr!
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write('Dispatched correctly.\n')

class campaignrslogimage(webapp.RequestHandler):

	def dumper(self):
		for key in self.request.params.keys():
			value = self.request.get(key)
			logging.info(key+':'+value+'\n')

	def post(self):

		Cametrics.initialize(config.cametricskey)

		#logging.info(dir(self.request))
		#logging.info(dir(self.request.body))
		#logging.info(dir(self.request.params.keys()))
		#logging.info(dir(self.request.environ.keys()))

		# This is what you really need
		logging.info(self.request.str_POST)
		logging.info(self.request.body)
		self.dumper()

		if(self.request.params.has_key('data_string')):

			latitude = ""
			longitude = ""
			image = ""
			type = ""
			timestamp = ""
			imei = ""

			dom = xml.dom.minidom.parseString(self.request.params['data_string'])
			rows = dom.getElementsByTagName("row")
			for row in rows:
				fields = row.getElementsByTagName("field")
				for field in fields:
					#logging.info(field.toxml())
					logging.info(field.attributes['name'].value)
					logging.info(field.firstChild.data)

					if(field.attributes['name'].value == "location"):
						location = simplejson.loads(field.firstChild.data)

						latitude = location["latitude"]
						longitude = location["longitude"]

						logging.info(latitude)
						logging.info(longitude)

					if(field.attributes['name'].value == "image"):
						image = field.firstChild.data

					if(field.attributes['name'].value == "type"):
						type = field.firstChild.data
						type = type.replace(" ", "")
						type = type.replace("[", "")
						type = type.replace("]", "")
						type = type.replace(' " ' , "")
						type = type.replace('"', "")
						type = type.replace(",", " ")
						type = type.lower()

					if(field.attributes['name'].value == "timestamp"):
						timestamp = field.firstChild.data.split("T")
						timestamp = timestamp[0]

                                        if(field.attributes['name'].value == "imei"):
                                                imei = field.firstChild.data

			logging.info(latitude)
			logging.info(longitude)
			logging.info(image)
			logging.info(type)
			logging.info(timestamp)
			logging.info(imei)

			# Cametrics Measurements
			Cametrics.measure("type", type, "string")
			Cametrics.measure("users", imei, "string")

                        if((str(latitude) != "nan") and (str(longitude) != "nan")):
				Cametrics.measure("locations", str(longitude)+","+str(latitude), "location")
				Cametrics.measure(type, str(longitude)+","+str(latitude), "location")
				Cametrics.measure(imei, str(longitude)+","+str(latitude), "location")

			Cametrics.commit()
				
			# This is to post things
	                # CONFIGURE: Replace this with your Flickr Information
			form_fields = config.getFlickrValues()
			form_fields.update({"tags":type+" "+imei, "latitude":str(latitude), "longitude":str(longitude), "image":image, "title":timestamp })

			form_data = urllib.urlencode(form_fields)
			result = urlfetch.fetch(url="http://whatsinvasive.com/research/slogtoflickr.php", payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, deadline=10)

			# This is to email stuff

			#geotags = ""
			#if((str(latitude) != "nan") and (str(longitude) != "nan")):
				# Lets add the GEO EXIF
			#	geotags = "geotagged " + "geo:lat="+str(latitude) + " " + "geo:lon=" + str(longitude)
			#fmsender = "thecleanmachine@gmail.com"
			#fmto = "dont87anti@photos.flickr.com"
			#fmsubject = timestamp + " tags: " + type + " " + imei + " " + geotags
			#fmbody = "Upladed via SenseTheBeach"
			#fmattachments = [(timestamp+".jpg",base64.decodestring(str(image)))]
			#mail.send_mail(sender=fmsender, to=fmto, subject=fmsubject, body=fmbody, attachments=fmattachments)

		# Return this for Cammpaignr!
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write('Dispatched correctly.\n')

application = webapp.WSGIApplication(
                                     [('/', main),
				     ('/participate', participate),
				     ('/document', document),
				     ('/map', map),
				     ('/campaignrslogimage', campaignrslogimage),
				     ('/campaignrsloglocation', campaignrsloglocation),
                                     ('/androidsloglocation', androidsloglocation),
                                     ('/androidslogmode', androidslogmode),
				     ('/androidslogimage', androidslogimage),
				     ('/stats', stats),
				     ('/statsmobile', statsmobile),
				     ('/mapmobile', mapmobile)],
                                     debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
